<template>
  <div class="debug-test">
    <h2>流式响应调试测试</h2>
    
    <div class="controls">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
        :disabled="isLoading"
      />
      <button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()">
        {{ isLoading ? '发送中...' : '发送' }}
      </button>
      <button @click="clearLogs">清空日志</button>
    </div>
    
    <div class="messages">
      <div 
        v-for="(msg, index) in messages" 
        :key="index"
        :class="['message', msg.type]"
      >
        {{ msg.content }}
      </div>
    </div>
    
    <div class="logs">
      <h3>调试日志</h3>
      <div class="log-content">
        <div v-for="(log, index) in logs" :key="index" class="log-item">
          {{ log }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DebugTest',
  data() {
    return {
      inputMessage: '',
      isLoading: false,
      messages: [],
      logs: []
    }
  },
  methods: {
    addLog(message) {
      const timestamp = new Date().toLocaleTimeString()
      this.logs.push(`[${timestamp}] ${message}`)
      // 保持日志数量在合理范围内
      if (this.logs.length > 100) {
        this.logs.shift()
      }
    },
    
    clearLogs() {
      this.logs = []
    },
    
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      const message = this.inputMessage.trim()
      this.inputMessage = ''
      this.isLoading = true
      
      this.addLog(`开始发送消息: ${message}`)
      
      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: message
      })
      
      // 添加AI消息占位符
      const aiMessageIndex = this.messages.length
      this.messages.push({
        type: 'assistant',
        content: ''
      })
      
      try {
        // 使用XMLHttpRequest进行测试
        const xhr = new XMLHttpRequest()
        
        xhr.open('POST', '/dev-api/api/ai/chat/send/stream', true)
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.setRequestHeader('Accept', 'text/event-stream')
        
        this.addLog('XMLHttpRequest已创建，准备发送请求')
        
        // 改进的SSE数据解析，处理数据分割问题
        let lastIndex = 0
        let buffer = ''
        const processChunk = () => {
          const newData = xhr.responseText.substring(lastIndex)
          if (!newData) return
          lastIndex = xhr.responseText.length
          
          // 将新数据添加到缓冲区
          buffer += newData
          this.addLog(`收到数据块111111111111111111111111111111111111111111111: ${newData}`)
          
          // 按行分割数据
          const lines = buffer.split('\n')
          
          // 保留最后一行（可能不完整）
          buffer = lines.pop() || ''
          
          // 处理完整的行
          for (const line of lines) {
            if (!line.trim()) continue
            
            if (line.startsWith('data: ')) {
              const payload = line.substring(6).trim()
              this.addLog(`提取payload: ${payload}`)
              
              if (payload === '[DONE]') {
                this.addLog('收到完成信号')
                this.isLoading = false
              } else if (payload) {
                try {
                  const parsed = JSON.parse(payload)
                  
                  if (parsed.content) {
                    this.addLog(`收到内容: ${parsed.content}`)
                    this.messages[aiMessageIndex].content += parsed.content
                  } else if (parsed.conversationId) {
                    this.addLog(`收到会话ID: ${parsed.conversationId}`)
                  }
                } catch (e) {
                  this.addLog(`JSON解析失败: ${e.message}, payload: ${payload}`)
                }
              }
            } else if (line.startsWith('{') && line.endsWith('}')) {
              // 处理没有"data: "前缀的JSON行
              try {
                const parsed = JSON.parse(line)
                
                if (parsed.content) {
                  this.addLog(`收到内容: ${parsed.content}`)
                  this.messages[aiMessageIndex].content += parsed.content
                } else if (parsed.conversationId) {
                  this.addLog(`收到会话ID: ${parsed.conversationId}`)
                }
              } catch (e) {
                this.addLog(`JSON解析失败: ${e.message}, line: ${line}`)
              }
            }
          }
        }
        
        xhr.onprogress = () => {
          this.addLog('onprogress触发')
          processChunk()
        }
        
        xhr.onreadystatechange = () => {
          this.addLog(`onreadystatechange触发, readyState: ${xhr.readyState}`)
          if (xhr.readyState === 3) {
            processChunk()
          } else if (xhr.readyState === 4) {
            this.addLog(`请求完成, status: ${xhr.status}`)
            processChunk()
            this.isLoading = false
          }
        }
        
        xhr.onerror = () => {
          this.addLog('请求发生错误')
          this.messages[aiMessageIndex].content = '请求失败'
          this.isLoading = false
        }
        
        const data = {
          message: message,
          userId: 'test-user',
          conversationId: null,
          createNewConversation: true
        }
        
        this.addLog(`发送数据: ${JSON.stringify(data)}`)
        xhr.send(JSON.stringify(data))
        
      } catch (error) {
        this.addLog(`异常: ${error.message}`)
        this.messages[aiMessageIndex].content = `错误: ${error.message}`
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped>
.debug-test {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.controls input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.controls button {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.controls button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.messages {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  height: 200px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.message {
  margin: 5px 0;
  padding: 8px;
  border-radius: 4px;
}

.message.user {
  background: #e3f2fd;
  text-align: right;
}

.message.assistant {
  background: #f1f8e9;
}

.logs {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  background: #f8f9fa;
}

.log-content {
  height: 300px;
  overflow-y: auto;
  font-family: monospace;
  font-size: 12px;
}

.log-item {
  margin: 2px 0;
  padding: 2px;
  border-bottom: 1px solid #eee;
}
</style>
